package chaw.android.train;

import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import chaw.android.util.HttpRequestManager;
import chaw.android.util.Preferences;
import chaw.android.util.ServerURL;

import android.app.ActivityGroup;
import android.app.ListActivity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class FavoriteStationListActivity extends ListActivity implements OnGestureListener{
	private ArrayList<JSONObject> json_list;
	private ArrayList<String> list;
	private ArrayAdapter<String> nadapter;
	private GestureDetector gesture;
	private String json_modify;
	
    private static final int SWIPE_MIN_DISTANCE = 120;
    private static final int SWIPE_MAX_OFF_PATH = 250;
    private static final int SWIPE_THRESHOLD_VELOCITY = 200;
	
	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.favorite_station_list);
	    json_modify = "";
		json_list = new ArrayList<JSONObject>();
		list = new ArrayList<String>();
		ListView lv = getListView();
		gesture = new GestureDetector(this);
		lv.setOnTouchListener(new View.OnTouchListener() {
		    @Override
			public boolean onTouch(View v, MotionEvent event) {
		    	if(gesture.onTouchEvent(event)){
	            	ActivityGroup parentActivity = (ActivityGroup) getParent();
	    			((FavoriteActivity) parentActivity).startChildActivityWithoutCurrentActivity("FavoritePeopleList",
	    						new Intent(getBaseContext(),FavoritePeopleListActivity.class));
		    	}
		    	return gesture.onTouchEvent(event);
		    }
		});
        
	}

	private void setListView(){
		DownloadAsynkTask task = new DownloadAsynkTask();
		String[] params = new String[]{ ServerURL.favoriteStation, "user_id", Preferences.getValue(getBaseContext(), "user_id")};
		task.execute(params);
	}
	
	private class DownloadAsynkTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			// TODO Auto-generated method stub
			String response = null;
			
			List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
			
			if(urls.length > 1)
				for(int i = 1; i< urls.length; i+=2)
					params.add(new BasicNameValuePair(urls[i], urls[i+1]));
			response = HttpRequestManager.request(urls[0], params);
			return response;
		}
		
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			json_list.clear();
			list.clear();
			json_modify = result;
			JSONArray json_arr;
			try {
				json_arr = new JSONArray(result);
				for(int i = 0 ; i < json_arr.length(); i++){
					JSONObject json_obj = (JSONObject) json_arr.get(i);
					json_list.add(json_obj);
				}
				Collections.sort(json_list, myComparator);
				for(int i = 0 ; i < json_list.size() ; i++){
					String station = (String)json_list.get(i).get("name");
					list.add(station);
				}
				nadapter = new ArrayAdapter<String>(getBaseContext(), R.layout.favorite_list_row, R.id.label2, list);
			    ListView lv = getListView();
			    lv.setAdapter(nadapter);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
	}


    private final static Comparator<JSONObject> myComparator= new Comparator<JSONObject>() {
        private final Collator collator = Collator.getInstance();
		@Override
		public int compare(JSONObject object1, JSONObject object2) {
        	try {
				return collator.compare(object1.get("name"), object2.get("name"));
			} catch (JSONException e) {
				e.printStackTrace();
				return 0;
			}
		}
    };

	@Override
	public void onListItemClick(ListView parent, View v, int position, long id){
		try {
			JSONObject output = json_list.get(position);
			String out = (String)output.get("station_id");
			String station_name = (String)output.get("name");

			ActivityGroup parentActivity = (ActivityGroup) getParent();
			Intent intent = new Intent(getBaseContext(), EachStationHome.class);
			intent.putExtra("station_id", out);
			intent.putExtra("station_name", station_name);
			((FavoriteActivity) parentActivity).startChildActivity("eachStationHome", intent);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
	}
	@Override
	public boolean onTouchEvent(MotionEvent me) {
        return gesture.onTouchEvent(me);
    }
	@Override
	public boolean onDown(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
		// TODO Auto-generated method stub
        try {
            if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
                return false;
            
            // right to left swipe
            if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
                    && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
        		return true;
            }
            else{
            	return false;
            }
        } catch (Exception e) {
        	return false;
        }
	}

	@Override
	public void onLongPress(MotionEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
		// TODO Auto-generated method stub
        return false;
	}

	@Override
	public void onShowPress(MotionEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		setListView();
	}
	
	public boolean onCreateOptionsMenu(Menu menu){
		menu.add(0, 1 , 0 , "관심역 수정");
		return true;
	}
	
	public boolean onOptionsItemSelected(MenuItem item){
		switch(item.getItemId()){
		case 1:
			if(!json_modify.equals("")){
				Intent intent = new Intent(getBaseContext(), ModifyStationListActivity.class);
				intent.putExtra("modify_list", json_modify);
				startActivity(intent);
				return true;
			}
			else{
				return false;
			}
		}
		return false;
	}
}
